
#include "stdafx.h"
#include "AddEntityWnd.h"
#include "Resource.h"
#include "MainFrm.h"
#include "OgitorWinMFC.h"


#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#endif


BEGIN_MESSAGE_MAP(CEntityView, CWnd)
	ON_WM_PAINT()
	ON_WM_SIZE()
	ON_WM_ERASEBKGND()
END_MESSAGE_MAP()

BOOL CEntityView::PreCreateWindow(CREATESTRUCT& cs) 
{
	if (!CWnd::PreCreateWindow(cs))
		return FALSE;

//	cs.dwExStyle |= WS_EX_CLIENTEDGE;
	cs.style &= ~WS_BORDER;
	cs.lpszClass = AfxRegisterWndClass(CS_HREDRAW|CS_VREDRAW|CS_DBLCLKS, 
		::LoadCursor(NULL, IDC_ARROW), reinterpret_cast<HBRUSH>(COLOR_WINDOW+1), NULL);

	return TRUE;
}

BOOL CEntityView::OnEraseBkgnd(CDC* pDC)
{
    return TRUE;
}

void CEntityView::OnPaint() 
{
	CPaintDC dc(this); // device context for painting
	
	if(!m_OgreInitialised)
	{
	 CRect rc;
	 GetClientRect(&rc);
	 dc.SelectObject(GetFont());
	 CBrush brush(RGB(0,0,0));
	 dc.FillRect(&rc,&brush);
	 dc.FillRect(&rc,&brush);
	}
    else
		;//m_Window->update(true);
       // m_UpdateNeeded = true;
}

void CEntityView::OnSize(UINT nType, int cx, int cy)
{
    CWnd::OnSize(nType, cx, cy);

    CRect rect; 
    GetClientRect(&rect); 
//     if (m_Window) 
//     { 
//         // notify "render window" instance 
//         m_Window->windowMovedOrResized(); 
// 
// 		if (rect.Width() > 1 && rect.Height() > 1)
// 		{
//             if(m_Camera != 0)
// 			{
// 			 m_Camera->setAspectRatio((Real)m_Window->getWidth() / (Real)m_Window->getHeight()); 
//              m_Camera->yaw(Radian(0));
// 			}
// 		}
//        // m_UpdateNeeded = true;
//     }
}

void CEntityView::AdjustCamera()
{
//  Vector3 vSize = m_DisplayEntity->getBoundingBox().getHalfSize();
//  Vector3 vCenter = m_DisplayEntity->getBoundingBox().getCenter(); 
 //float x = m_DisplayEntity->getBoundingRadius();
// 
//  float maxsize = max(max(vSize.x,vSize.y),vSize.z);
//  
//  vSize = (Vector3(maxsize,maxsize,maxsize) + vCenter) * 2.0f;

 //m_Camera->setPosition(vCenter.x,vCenter.y,vCenter.z + maxsize);
//  m_Camera->setPosition(vSize.x,vSize.y,vSize.z);
//  m_Camera->lookAt(vCenter.x,vCenter.y,vCenter.z);
 Invalidate();
}

void CEntityView::SetupOgre()
{
//  m_OgreRoot = theApp.GetOgreRoot();
//  m_OgreRoot->addFrameListener(this);
//  NameValuePairList parms;
//  parms["externalWindowHandle"] = StringConverter::toString((long)m_hWnd);

 CRect   rect;
 GetClientRect(&rect);

//  m_Window = m_OgreRoot->createRenderWindow("Entity Window", rect.Width(), rect.Height(), false, &parms);
// 
//  StringVectorPtr pList = ResourceGroupManager::getSingleton().findResourceNames("ProjectResources","*.mesh",false);
//  CListBox *pListWnd = &(((CAddEntityWnd *)GetParent())->m_wndList);
//  for(unsigned int i = 0;i < pList->size();i++)
//  {
// 	 String addstr = (*pList)[i];
// 	 if(pListWnd->FindString(-1,CString(addstr.c_str())) == LB_ERR)
// 	    pListWnd->AddString(CString(addstr.c_str()));
//  }
//  pListWnd->SetCurSel(0);
//  pList.setNull();
//  //m_UpdateNeeded = true;
//  m_Window->setAutoUpdated(false);
}
// <lights>
// <light name="Omni01" type="omni" on="true" CastShadows="yes" intensity="1">
// <position x="-3.39464" y="2.19248" z="11.28"/>
// <rotation x="0" y="0" z="0" w="1"/>
// <scale x="1" y="1" z="1"/>
// <color r="1" g="0.984314" b="0.941176"/>
 
 
 
 
 
void CEntityView::LoadEditorObjects()
{
//  m_SceneManager = m_OgreRoot->createSceneManager("OctreeSceneManager","EntityViewManager");
//  m_SceneManager->setAmbientLight(ColourValue(0.5,0.5,0.5));
// 
//  Light *dirl = m_SceneManager->createLight("view_Omni01");
//  dirl->setPosition(-3.39464,2.19248,11.28);
//  dirl->setDiffuseColour(1,0.984314,0.941176);
//  dirl->setSpecularColour(0,0,0);
//  dirl->setType(Light::LT_POINT);
// 
//  Light *dirl2 = m_SceneManager->createLight("view_Omni02");
//  dirl2->setPosition(-2.50578,0.487743,-0.939424);
//  dirl2->setDiffuseColour(0,0.223529,0.501961);
//  dirl2->setSpecularColour(0,0,0);
//  dirl2->setType(Light::LT_POINT);
// 
// 
//  Light *dirl3 = m_SceneManager->createLight("view_Omni03");
//  dirl3->setPosition(0,3.67441,-0.993758);
//  dirl3->setDiffuseColour(0.6,0.6,0.6);
//  dirl3->setSpecularColour(0.6,0.6,0.6);
//  dirl3->setType(Light::LT_POINT);
// 
// 
//  Light *dirl4 = m_SceneManager->createLight("view_Omni04");
//  dirl4->setPosition(3.8476,0.905195,0.387301);
//  dirl4->setDiffuseColour(0.501961,0.145098,0);
//  dirl4->setSpecularColour(0,0,0);
//  dirl4->setType(Light::LT_POINT);



 //  Light *dirl = m_SceneManager->createLight("DisplayLight");
//  dirl->setDirection(-1,-1,-1);
//  dirl->setDiffuseColour(0.7,0.7,0.7);
//  dirl->setType(Light::LT_DIRECTIONAL);

//  m_Camera = m_SceneManager->createCamera("EntityCam");
//  m_Camera->setPosition(0,50,200);
//  m_Camera->lookAt(0,0,0);
//  m_Camera->setNearClipDistance(0.1);
//  m_Camera->setFarClipDistance(10000);
//  m_SceneManager->getRootSceneNode()->attachObject(m_Camera);
// 
//  Viewport* vp = m_Window->addViewport(m_Camera);
//  vp->setBackgroundColour(ColourValue(0,0,0));
//   
//  CRect rc;
//  GetClientRect(&rc);
//  m_Camera->setAspectRatio(Real(rc.Width()) / Real(rc.Height()));
// 
//  m_OgreInitialised = true;
//  ((CAddEntityWnd *)GetParent())->OnSelectionChanged();
}

void CEntityView::TerminateOgre()
{
// 	 m_OgreRoot->removeFrameListener(this);
//  if(!m_OgreInitialised) return;
//  m_DisplayEntity = 0;
//  m_Camera = 0;
//  m_OgreInitialised = false;
//  m_Window->removeAllViewports();
//  m_OgreRoot->detachRenderTarget("Entity Window");
//  CListBox *pListWnd = &(((CAddEntityWnd *)GetParent())->m_wndList);
//  while(pListWnd->GetCount()) 
//    pListWnd->DeleteString(0);
//  m_OgreRoot->destroySceneManager(m_SceneManager);
//  m_SceneManager = 0;
//  m_UpdateNeeded = false;
 Invalidate();
}

void CEntityView::DisplayMesh(String name)
{
//  if(!name.empty())
//  {
//   if(m_DisplayEntity)
//   {
//    DETACHFROMPARENT(m_DisplayEntity);
//    m_DisplayEntity->_getManager()->destroyEntity(m_DisplayEntity);
//    m_DisplayEntity = 0;
//   }
//   m_DisplayEntity = m_SceneManager->createEntity("scbDisplay",name);
//   m_SceneManager->getRootSceneNode()->attachObject(m_DisplayEntity);
//   AdjustCamera();
//   //create animation
//   mAnimStates = NULL;
//   if (m_DisplayEntity->hasSkeleton() )
//   {
// 
// 	  StringVector AnimationList;
// 	  SkeletonInstance * ins = m_DisplayEntity->getSkeleton();
// 	  for (int i =0 ;i < ins->getNumAnimations();++i)
// 	  {
// 		  Animation* ani = ins->getAnimation(i) ;
// 		  AnimationList.push_back(ani->getName());
// 	  }
// 	  if (AnimationList.size()>0)
// 	  {
// 		  mAnimStates = 
// 			  mAnimStates = m_DisplayEntity->getAnimationState(AnimationList.at(0));
// 		  if (mAnimStates->getLength()>0)
// 		  {
// 			  mAnimStates->setEnabled(true);
// 			  mAnimStates->setLoop(true);
// 		  }
// 
// 	  }
// 
// 
//   }
//   //create mat
//   for (int i=0;i< m_DisplayEntity->getNumSubEntities();++i)
//   {
// 
// 	  MaterialPtr   mat = m_DisplayEntity->getSubEntity(i)->getMaterial();
// 	  Pass* pass = mat->getTechnique(0)->getPass(0);
// 	  if (pass)
// 	  {
// 
// 		  if (/*!pass->hasFragmentProgram()&&!pass->hasVertexProgram()&&*/pass->getNumTextureUnitStates()==3)
// 		  {
// 			pass->setFragmentProgram("PS_Normal_Skin");
// 			pass->setVertexProgram("VS_Normal_Skin");
// 			m_DisplayEntity->getSubEntity(i)->setMaterialName(m_DisplayEntity->getSubEntity(i)->getMaterialName());
// 		  }
// 		  else
// 		  {
// 			  pass->setFragmentProgram("");
// 			  pass->setVertexProgram("");
// 			  m_DisplayEntity->getSubEntity(i)->setMaterialName(m_DisplayEntity->getSubEntity(i)->getMaterialName());
// 		  }
// 
// 	  }
// 
//   }
//  // m_UpdateNeeded = true;
//  }
}

bool CEntityView::frameStarted(/*const FrameEvent& evt*/)
{
	//updata animation
// 	if (mAnimStates&&mAnimStates->getLength()>0)
// 	{
// 		mAnimStates->addTime(evt.timeSinceLastFrame);
// 	}

	return true;
}

CAddEntityWnd::CAddEntityWnd()
{
 m_SelectedEntity = "";
}

CAddEntityWnd::~CAddEntityWnd()
{
}

BEGIN_MESSAGE_MAP(CAddEntityWnd, CDockablePane)
	ON_WM_CREATE()
	ON_WM_SIZE()
 	ON_WM_CLOSE()
	ON_LBN_SELCHANGE(ID_ADDENTITY_LIST,OnSelectionChanged)
	ON_BN_CLICKED(ID_ADDENTITY_ADDBTN,OnAddToSceneClick)
	ON_UPDATE_COMMAND_UI(ID_ADDENTITY_ADDBTN,OnUpdateAddBtn)
END_MESSAGE_MAP()

int CAddEntityWnd::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CDockablePane::OnCreate(lpCreateStruct) == -1)
		return -1;

	m_Font.CreateFont(14,0,0,0,FW_NORMAL,FALSE,FALSE,0,ANSI_CHARSET,OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY,DEFAULT_PITCH | FF_SWISS,_T("Arial"));

	CRect rc;
	GetClientRect(&rc);
	if (!m_wndEntityView.Create(NULL, NULL, AFX_WS_DEFAULT_VIEW, CRect(150, 0, rc.right - 1, rc.bottom - 1), this, ID_ADDENTITY_VIEW, NULL))
	{
		TRACE0("Failed to create entity view window\n");
		return -1;
	}
	if (!m_wndList.Create(LBS_NOINTEGRALHEIGHT | LBS_STANDARD, CRect(0, 0, 150, rc.bottom - 26), this, ID_ADDENTITY_LIST))
	{
		TRACE0("Failed to create listbox window\n");
		return -1;
	}
	if (!m_AddButton.Create(_T("Add to Scene"),BS_TEXT|BS_NOTIFY|BS_CENTER|BS_VCENTER|BS_PUSHBUTTON, CRect(0,rc.bottom - 26, 150, rc.bottom), this, ID_ADDENTITY_ADDBTN))
	{
		TRACE0("Failed to create listbox window\n");
		return -1;
	}
	m_AddButton.SetFont(&m_Font,true);
	m_wndList.SetFont(&m_Font,true);
	m_wndEntityView.SetFont(&m_Font,true);

	m_wndList.ShowWindow(SW_SHOW);
	m_AddButton.ShowWindow(SW_SHOW);
	return 0;
}

void CAddEntityWnd::OnSize(UINT nType, int cx, int cy)
{
	CDockablePane::OnSize(nType, cx, cy);
	CRect rc;
	GetClientRect(&rc);
    int eqHeight = (rc.Height() - 26) / 2;
	m_wndList.SetWindowPos(NULL,0,0,rc.Width(),eqHeight,0);
	m_wndEntityView.SetWindowPos(NULL,0,eqHeight,rc.Width(),eqHeight,0);
	m_AddButton.SetWindowPos(NULL,0,eqHeight * 2,rc.Width(),rc.Height() - (2 * eqHeight),0);
}

void CAddEntityWnd::OnClose()
{
    ShowWindow(SW_HIDE);
}

void CAddEntityWnd::OnSelectionChanged()
{
 if(!m_wndEntityView.m_OgreInitialised) return;
 int curID = m_wndList.GetCurSel();
 if(curID == -1) return;
 m_wndList.GetText(curID,m_SelectedEntity);
 m_wndEntityView.DisplayMesh(ConvertToApoString(m_SelectedEntity));
}

void CAddEntityWnd::OnAddToSceneClick()
{
//     CViewportEditor *ovp = ClientRoot::getSingletonPtr()->GetViewport();
//     if(ovp)
//         ovp->TryAddObject("Entity Object", ConvertToOgreString(m_SelectedEntity));
}

void CAddEntityWnd::OnUpdateAddBtn(CCmdUI *pCmdUI)
{
}